package javase.javase01.exercise09;

/**
 * @author: Gan
 * @date 2021/4/12 0012 21:15
 * @description: 深度克隆练习
 * * - 现在有三个类 FirstLevel 、SecondLevel 、ThirdLevel
 * *
 * * - FirstLevel 类有三个属性
 * *     int firstIntValue;
 * *     double firstDoubleValue;
 * *     SecondLevel second;
 * *
 * * - SecondLevel 类有三个属性
 * *     int secondIntValue;
 * *     double secondDoubleValue;
 * *     ThirdLevel third;
 * *
 * * - ThirdLevel 类有两个属性
 * *     int thirdIntValue;
 * *     double thirdDoubleValue;'
 * *
 * * 想要对FirstLevel做深度克隆:
 * * 首先要明确,需要对几个类做深度克隆? 需要对两个类做深度克隆
 * * 要对几个类做浅克隆呢? 三个
 * * 浅克隆的条件:
 * * 重写权限
 * * 实现空接口
 **/
public class Demo1 {
    public static void main(String[] args) throws CloneNotSupportedException {
        FirstLevel f = new FirstLevel(1, 2.3,
                new SecondLevel(2, 3.4,
                        new ThirdLevel(4, 3.6)));
        FirstLevel firstLevel = f.clone();
        System.out.println(firstLevel.second == f.second);
        System.out.println(firstLevel.second.third == f.second.third);
    }
}

class FirstLevel implements Cloneable {
    int firstIntValue;
    double firstDoubleValue;
    SecondLevel second;

    public FirstLevel(int firstIntValue, double firstDoubleValue, SecondLevel second) {
        this.firstIntValue = firstIntValue;
        this.firstDoubleValue = firstDoubleValue;
        this.second = second;
    }

    @Override
    protected FirstLevel clone() throws CloneNotSupportedException {
        //浅克隆，来自object类的
        FirstLevel f = (FirstLevel) super.clone();
        //克隆引用 继续克隆clone
        f.second = this.second.clone();
        return f;
    }
}

class SecondLevel implements Cloneable {
    int secondIntValue;
    double secondDoubleValue;
    ThirdLevel third;

    public SecondLevel(int secondIntValue, double secondDoubleValue, ThirdLevel third) {
        this.secondIntValue = secondIntValue;
        this.secondDoubleValue = secondDoubleValue;
        this.third = third;
    }

    @Override
    protected SecondLevel clone() throws CloneNotSupportedException {
        SecondLevel secondLevel = ((SecondLevel) super.clone());
        secondLevel.third = this.third.clone();
        return secondLevel;
    }
}

class ThirdLevel implements Cloneable{
    int thirdIntValue;
    double thirdDoubleValue;

    public ThirdLevel(int thirdIntValue, double thirdDoubleValue) {
        this.thirdIntValue = thirdIntValue;
        this.thirdDoubleValue = thirdDoubleValue;
    }

    @Override
    protected ThirdLevel clone() throws CloneNotSupportedException {
        return ((ThirdLevel) super.clone());
    }
}